package com.jzr.board.ui

import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.view.View
import android.widget.CompoundButton
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.utils.*
import com.jzr.board.R
import com.jzr.board.base.BaseActivity
import com.jzr.board.base.BaseApplication
import com.jzr.board.bean.*
import com.jzr.board.bean.body.RecordBody
import com.jzr.board.presenter.contract.SettingActivityContract
import com.jzr.board.presenter.impl.SettingActivityImpl
import com.jzr.board.ui.adapter.CheckDeptApadter
import com.jzr.board.utils.CommonUtil
import com.jzr.board.utils.DownloadFileListener
import com.jzr.board.utils.OkHttpUtil
import com.jzr.board.utils.PreferUtil
import com.jzr.board.view.CustomDialog
import kotlinx.android.synthetic.main.actionbar_root_layout.*
import kotlinx.android.synthetic.main.include_setting_system.*
import kotlinx.android.synthetic.main.include_setting_system_info.*
import java.io.File
import java.lang.Exception

class SystemSettingActivity : BaseActivity(), SettingActivityContract.View, View.OnClickListener,
    CompoundButton.OnCheckedChangeListener, CheckDeptApadter.onListItemClick {

    private val mPresenter = SettingActivityImpl(this)

    private var apadter: CheckDeptApadter? = null
    private var dialogDeptList: CustomDialog? = null
    private var code: String? = null
    private var name: String? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_system_setting
    }

    override fun attachView() {
        mPresenter.attachView(this)
    }

    override fun detachView() {
        mPresenter.detachView()
    }

    override fun initView() {

        edServiceIp.setText(PreferUtil.getInstance().serviceIp)
        edServicePort.setText(PreferUtil.getInstance().serverPort)

        switchWifi.isChecked = NetworkUtils.isWifiConnected()
        switchWifi.setOnCheckedChangeListener(this)
        tvWifiInfo.text = CommonUtil.getWifiInfo(this)

        tvSnInfo.text = Build.SERIAL
        tvIpInfo.text = CommonUtil.getIP()
        tvVersionInfo.text = AppUtils.getAppVersionName(this)
        tvMacInfo.text = DeviceUtils.getMacAddress()
        tvWebSocket.setText(PreferUtil.getInstance().websocket)

        edBedPrefix.setText(PreferUtil.getInstance().bedPrefix)
        edInFlag.setText(PreferUtil.getInstance().inFlag)


        butConnecttest.setOnClickListener(this)
        tvCheckDeptNo.setOnClickListener(this)
        btCheckDeptNo.setOnClickListener(this)
        btWebSocket.setOnClickListener(this)
        ivRight.setOnClickListener(this)
        rlUpdate.setOnClickListener(this)

        mPresenter.getDeviceInfo("deviceNo", Build.SERIAL)

    }

    override fun onDestroy() {
        super.onDestroy()
        PreferUtil.getInstance().serviceIp = edServiceIp.text.toString()
        PreferUtil.getInstance().serverPort = edServicePort.text.toString()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.ivRight -> {  // 退出
                finish()
            }
            R.id.btWebSocket -> {  // websocket
                PreferUtil.getInstance().setWebSocket( tvWebSocket.text.toString())
            }
            R.id.btCheckDeptNo -> {

                PreferUtil.getInstance().bedPrefix = edBedPrefix.text.toString().trim()
                PreferUtil.getInstance().inFlag = edInFlag.text.toString().trim()

                val body = RecordBody()
                body.appVersion = AppUtils.getAppVersionCode(this)
                body.deptCode = PreferUtil.getInstance().deptCode
                body.deviceIp = CommonUtil.getIP()
                body.deviceMac = DeviceUtils.getMacAddress()
                body.deviceNo = Build.SERIAL
                body.deviceType = 1
                body.registerBed = PreferUtil.getInstance().bedCode
                mPresenter.getBindingDeptNo(body)

            }
            R.id.butConnecttest -> {
                PreferUtil.getInstance().serviceIp = edServiceIp.text.toString()
                PreferUtil.getInstance().serverPort = edServicePort.text.toString()
//                mPresenter.connectTest()
                mPresenter.getDeviceInfo("deviceNo", Build.SERIAL)
            }
            R.id.tvCheckDeptNo -> {
                mPresenter.getCheckDeptNo()
            }
            R.id.rlUpdate -> {
                mPresenter.getLastVersion(this,"softType","1")
            }
        }
    }

    override fun connectTestSuccess(data: ConnectTestBean?) {
        ToastUtils.showShortToast("连接成功")
    }

    override fun getBindingDeptNoSuccess(data: BindingDeptBean?) {
        PreferUtil.getInstance().deptCode = code
        PreferUtil.getInstance().deptName = name
        ToastUtils.showShortToast("绑定科室成功")
    }

    override fun getCheckDeptNoSuccess(data: DeptCodeListBean?) {
        ToastUtils.showShortToast("连接成功")
        showDeptListDialog(data)
    }

    override fun getDeviceInfoSuccess(data: DeviceInfoBean?) {
        if (data?.data?.registerState == 1) {   //绑定的状态 0:未绑定 1:绑定中
            tvCheckDeptNo.text = data.data?.deptName
        }
    }

    override fun getLastVersionSuccess(data: LastVersionBean?) {
        val path =
            Environment.getExternalStorageDirectory().path + "/JzrApk/"
        if (AppUtils.getAppVersionCode(this) < data?.data?.version!!) {
            showLoadingDialog("正在下载.....")
            OkHttpUtil.download(data.data?.url, path, object : DownloadFileListener {
                override fun onDownloading(progress: Int) {
                    LogUtils.e("name", "progress == $progress")

                }

                override fun onDownloadFailed(e: Exception?) {
                    dismissLoadingDialog()
                    runOnUiThread {
                        ToastUtils.showShortToast("下载失败...")
                    }
                }

                override fun onDownloadSuccess(file: File?) {
                    dismissLoadingDialog()
                    runOnUiThread {
                        ToastUtils.showShortToast("下载成功...")
                    }
                    CommonUtil.installApk(this@SystemSettingActivity,file!!)
                }
            })
        }else{
            ToastUtils.showShortToast("无新版本...")
        }

    }

    override fun showError(message: String?) {
        ToastUtils.showShortToast(message)
    }

    private fun showDeptListDialog(checkDeptBean: DeptCodeListBean?) {
        hideDeptListDialog()
        val view =
            View.inflate(BaseApplication.getContext(), R.layout.dialog_dept_list, null)
        val rvDeptList = view.findViewById<RecyclerView>(R.id.rv_dept_list)

        val checkDataBeanList = mutableListOf<BaseCheckDataBean>()
        for (item in checkDeptBean!!.data) {
            val checkDataBean = BaseCheckDataBean()
            checkDataBean.code = item?.code
            checkDataBean.name = item?.name
            checkDataBeanList.add(checkDataBean)

        }

        apadter = CheckDeptApadter(checkDataBeanList)
        rvDeptList.layoutManager = LinearLayoutManager(this)
        rvDeptList.adapter = apadter
        dialogDeptList = CustomDialog(this, 500,500,view, R.style.MyDialog)
        dialogDeptList?.setCancelable(true)
        dialogDeptList?.show()
        apadter?.setAdapterType(0)
        apadter?.onListItemClick(this)

    }

    private fun hideDeptListDialog() {
        if (dialogDeptList != null && dialogDeptList?.isShowing!!) {
            dialogDeptList?.dismiss()
            dialogDeptList = null
        }
    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        if (!isChecked) {
            tvWifiInfo.text = ""
        } else {
            tvWifiInfo.text = CommonUtil.getWifiInfo(this)
        }
        NetworkUtils.setWifiEnabled(isChecked)
    }

    override fun onListItemClick(item: BaseCheckDataBean?) {
        hideDeptListDialog()
        code = item?.code
        name = item?.name
        tvCheckDeptNo.text = item?.name
        PreferUtil.getInstance().deptCode = code

    }

}
